package com.shiliao.framework.ui.widght;

import android.content.Context;
import android.graphics.Canvas;
import android.support.v7.widget.AppCompatTextView;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;


/**
 * 统一的TextView，用于统一控制，如字体等
 *
 * @author yjl
 */
public class YimeiText extends AppCompatTextView {

    // 以下Flag表示该控件的作用
    public static final int YIMEI_DISPLAY_MORE = 1;        //“显示更多”按钮
    public static final int YIMEI_AD_BTN = 2;        // 按钮
    public static final int YIMEI_INTRODUCTION = 3;        // 详情页简介页面
    public static final int YUIMEI_NULL = -1;

    private static final String ELLIPSIS = "...";

    private int bussFlag = YUIMEI_NULL;
    private View correlationFun = null;//更多按钮

    private boolean isEllipsized;
    private boolean isStale;
    private boolean programmaticChange;
    private String fullText;
    private int maxLines = -1;
    private float lineSpacingMultiplier = 1.0f;
    private float lineAdditionalVerticalPadding = 0.0f;

    public interface EllipsizeListener {
        void ellipsizeStateChanged(boolean ellipsized);
    }

    private final List<EllipsizeListener> ellipsizeListeners = new ArrayList<EllipsizeListener>();

    public YimeiText(Context context) {
        this(context, null);
    }

    public YimeiText(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public YimeiText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        //初始化字体
        //TODO 自定义字体打开这部分代码就可以了
//		Typeface typeface = TypefaceUtil.getInstance()
//				.getTypeface(getContext());
//		Typeface oldTypeFace = getTypeface();
//
//		if (typeface == null) {
//			return;
//		}
//		if (null != oldTypeFace) {
//			setTypeface(typeface, oldTypeFace.getStyle());
//		} else {
//			setTypeface(typeface);
//		}
    }

    public void setBussFlag(int flag) {
        this.bussFlag = flag;
    }

    public int getBussFlag() {
        return this.bussFlag;
    }

    public void setCorrelationFun(View obj) {
        this.correlationFun = obj;
    }

    @Override
    // 重写onDraw方法，主要为解决以下问题
    // 问题描述：
    // 简介只有两行，但显示时仍有查看更多按钮，点击后没有更多内容显示
    // 按钮消失后导致整个页面往上移。建议根据内容多少来判定是否需要显示查看更多的按钮
    protected void onDraw(Canvas canvas) {
        if (this.bussFlag != YIMEI_DISPLAY_MORE) {
            super.onDraw(canvas);
            return;
        }

        if (isStale) {
            super.setEllipsize(null);
            resetText();
        }

        super.onDraw(canvas);

        switch (bussFlag) {
            case YIMEI_DISPLAY_MORE:
                if (isEllipsized) {
                    if (correlationFun != null) {
                        this.correlationFun.setVisibility(View.VISIBLE);
                        this.correlationFun = null;
                    }
                } else {
                    if (correlationFun != null) {
                        this.correlationFun.setVisibility(View.GONE);
                        this.correlationFun = null;
                    }
                }

                break;
            default:
                break;
        }
    }

    public void addEllipsizeListener(EllipsizeListener listener) {
        if (listener == null) {
            throw new NullPointerException();
        }
        ellipsizeListeners.add(listener);
    }

    public void removeEllipsizeListener(EllipsizeListener listener) {
        ellipsizeListeners.remove(listener);
    }

    public boolean isEllipsized() {
        return isEllipsized;
    }

    @Override
    public void setMaxLines(int maxLines) {
        super.setMaxLines(maxLines);
        this.maxLines = maxLines;
        isStale = true;
    }

    public int getMaxLines() {
        return maxLines;
    }

    @Override
    public void setLineSpacing(float add, float mult) {
        this.lineAdditionalVerticalPadding = add;
        this.lineSpacingMultiplier = mult;
        super.setLineSpacing(add, mult);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int before,
                                 int after) {
        super.onTextChanged(text, start, before, after);
        if (!programmaticChange) {
            fullText = text.toString();
            isStale = true;
        }
    }

    private void resetText() {
        int maxLines = getMaxLines();
        String workingText = fullText;
        boolean ellipsized = false;
        if (maxLines != -1) {
            Layout layout = createWorkingLayout(workingText);
            if (layout.getLineCount() > maxLines) {
                workingText = fullText.substring(0,
                        layout.getLineEnd(maxLines - 1) - 1);
                workingText = workingText.replaceAll(" ", "");
                Layout layout2 = createWorkingLayout(workingText + ELLIPSIS);
                while (layout2.getLineCount() > maxLines) {
                    int lastSpace = workingText.lastIndexOf(' ');
                    if (lastSpace == -1) {
                        break;
                    }
                    workingText = workingText.substring(0, lastSpace);
                }
                workingText = workingText + ELLIPSIS;
                ellipsized = true;
            }
        }
        if (!workingText.equals(getText())) {
            programmaticChange = true;
            try {
                // 重新setText会导致原字符串格式出错，如《编辑推荐》《作者简介》几个字加粗，暂时屏蔽
                //	setText(workingText);
            } finally {
                programmaticChange = false;
            }
        }
        isStale = false;
        if (ellipsized != isEllipsized) {
            isEllipsized = ellipsized;
            for (EllipsizeListener listener : ellipsizeListeners) {
                listener.ellipsizeStateChanged(ellipsized);
            }
        }
        // 重新setText会导致原字符串格式出错几个字加粗，暂时屏蔽
//		setText(fullText);
    }

    private Layout createWorkingLayout(String workingText) {
        return new StaticLayout(workingText, getPaint(), getWidth()
                - getPaddingLeft() - getPaddingRight(), Alignment.ALIGN_NORMAL,
                lineSpacingMultiplier, lineAdditionalVerticalPadding, false);
    }

    @Override
    public void setEllipsize(TruncateAt where) {
        if (this.bussFlag != YIMEI_DISPLAY_MORE) {
            super.setEllipsize(where);
        }
        // Ellipsize settings are not respected } }
    }
}
